package jmine.tec.script.persistent.persister;

import static jmine.tec.script.persistent.domain.enumx.BaseScriptPurposeIdentifier.API;
import static jmine.tec.script.persistent.domain.enumx.BaseScriptPurposeIdentifier.INIT;

import java.util.List;

import jmine.tec.annotations.Unmodifiable;
import jmine.tec.script.persistent.dao.ScriptDAO;
import jmine.tec.script.persistent.domain.Script;
import bancosys.tec.persist.persister.listener.AbstractPersisterListener;

/**
 * @author lundberg
 */
@Unmodifiable
public class ScriptPersisterListener extends AbstractPersisterListener<Script> {

    private final ScriptDAO scriptDAO;

    /**
     * Constructor
     * 
     * @param scriptDAO scriptDAO
     */
    public ScriptPersisterListener(ScriptDAO scriptDAO) {
        this.scriptDAO = scriptDAO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterUpdate(Script bean) {
        bean.recalculateVersion();
        this.incrementDependentScriptsVersions(bean);
    }

    /**
     * Increments all dependent scripts versions. Necessary to notify script executors that it is necessary do resolve the script's body
     * again, invalidating any generated caches.
     * 
     * @param script script
     */
    protected void incrementDependentScriptsVersions(Script script) {
        if (script.getPurpose().isIdentifiedBy(API)) {
            this.incrementVersions(this.scriptDAO.findByAPI(script));
        }
        if (script.getPurpose().isIdentifiedBy(INIT)) {
            this.incrementVersions(this.scriptDAO.findByInitScript(script));
        }
    }

    /**
     * Increments the version of all scripts
     * 
     * @param scripts scripts
     */
    private void incrementVersions(List<Script> scripts) {
        for (Script script : scripts) {
            script.recalculateVersion();
            script.setVersion(script.getVersion() + 1);
        }
    }
}
